import { ArticleService } from './../service/article.service';
import { AbstractController, Restful, Router, Autowire } from "ts-express-restful";
import { Request, Response } from "express-serve-static-core";
import { NextFunction } from "connect";
import CustomerError from "../error";
import { getValue, L } from "../i18n";

@Restful()
export class ArticleController extends AbstractController { 

    @Autowire
    public articleService!: ArticleService;

    $isValidId(id: string) { 
        return /^\d+$/.test(id);
    }

    @Router("/all")
    async all(req: Request, res: Response, next: NextFunction) { 
        let result = await this.articleService.all({ where: {} });
        res.json(result);
    }

    async find(req: Request, res: Response, next: NextFunction) { 
        let { page=0, pagesize=20 } = req.query;
        let pager = await this.articleService.find({
            where: {},
        }, page, pagesize);
        res.json(pager);
    }

    async get(req: Request, res: Response, next: NextFunction) { 
        let { id } = req.params;
        let { lang } = req.query;
        let article = await this.articleService.get(id);
        if (!article) { 
            const articleName = getValue(lang, L.ARTICLE);
            return next(new CustomerError(404, getValue(lang, L.NOT_FOUND, articleName)));
        }
        res.json(article);
    }
}